package cn.tedu.hotel.serve.config;


import cn.tedu.hotel.serve.filter.JwtAuthorizationFilter;
import cn.tedu.hotel.serve.web.JsonResult;
import cn.tedu.hotel.serve.web.ServiceCode;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder(){
        /*return NoOpPasswordEncoder.getInstance();*/
        return new BCryptPasswordEncoder();
    }
    @Autowired
    JwtAuthorizationFilter jwtAuthorizationFilter;

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //不使用session
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        http.addFilterBefore(jwtAuthorizationFilter, UsernamePasswordAuthenticationFilter.class);
        //处理为通过认证导致的拒绝访问
        http.exceptionHandling().authenticationEntryPoint(new AuthenticationEntryPoint() {
            @Override
            public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
                response.setContentType("application/json; charset=utf-8");
                String message = "您当前未登录，请登录！";
                log.warn("{}", message);
                PrintWriter writer = response.getWriter();
                JsonResult<Void> jsonResult=JsonResult.fail(ServiceCode.ERROR_UNAUTHORIZED,message);
                String jsonString = JSON.toJSONString(jsonResult);
                writer.println(jsonString);
                writer.close();
            }
        });

        http.csrf().disable();

        //option请求方式
        http.cors();

        /*super.configure(http);*///不要求保留

        String[] urls={
                "/user/addHotelScore",
                "/user/addHotelScore",
                "/user/addOrder",
                "/user/getCurrentRoomsByThreeColumn",
                "/user/addUserComment",
                "/*/admin/**"
        };

        http.authorizeRequests()//对请求进行授权
                //也能够放行option
                /*.mvcMatchers(HttpMethod.OPTIONS,"/**")
                .permitAll()*/
                .mvcMatchers(urls)//匹配某些路径
                .authenticated()//要求认证通过
                .anyRequest()//任意请求
                .permitAll();//直接许可不惜要认证



        // 如果调用以下方法，当需要访问通过认证的资源，但是未通过认证时，将自动跳转到登录页面
        // 如果未调用以下方法，将响应403
        //http.formLogin();

        //TODO 回来修改权限
    }
}
